import json
from django.core.cache import cache as mem_cache
from celery import shared_task
from celery.task import periodic_task
from django import template
from stocksys import models as stocksys_models
from Library_WEB import settings
from stocksys.sys_tasks.logic_function import DjangoTask, get_realtime_stock_content, workDay, stock_report, \
    onMarketOpenWork
from stocksys.views.data_logic import send_email_message


@periodic_task(run_every=2)
def update_mystock():
    '''
    更新自选数据
    :return:
    '''
    if workDay():
    # if True:
        mystocks = stocksys_models.MyStcock.objects.all()
        for mystock in mystocks:
            _stock = mystock.stock.stock
            stock_code = "%s%s" % (_stock.exchange_address.stock_sina_name, _stock.code)
            # 通过新浪API获取实时数据
            stock = get_realtime_stock_content(stock_code)
            # print("更新自选数据:%s %s" % (stock_code, _stock.name))
            # print(stock)
            # 将实时数据更新到数据库
            stock_realtime_info = stocksys_models.StockInfo.objects.get(sysconf=mystock.sysconf, stock=_stock)
            stock_realtime_info.today_open = stock['open']
            stock_realtime_info.yestoday_close = stock['close']
            stock_realtime_info.current_price = stock['current']
            stock_realtime_info.high = stock['high']
            stock_realtime_info.low = stock['low']
            stock_realtime_info.volume = stock['v_num']
            stock_realtime_info.money = stock['money']
            # 买1
            stock_realtime_info.call_auction_a1_p = stock['a1_v']
            stock_realtime_info.call_auction_a1_v = stock['a1_p']
            # 买2
            stock_realtime_info.call_auction_a2_p = stock['a2_v']
            stock_realtime_info.call_auction_a2_v = stock['a2_p']
            # 买3
            stock_realtime_info.call_auction_a3_p = stock['a3_v']
            stock_realtime_info.call_auction_a3_v = stock['a3_p']
            # 买4
            stock_realtime_info.call_auction_a4_p = stock['a4_v']
            stock_realtime_info.call_auction_a4_v = stock['a4_p']
            # 买5
            stock_realtime_info.call_auction_a5_p = stock['a5_v']
            stock_realtime_info.call_auction_a5_v = stock['a5_p']

            # 卖1
            stock_realtime_info.call_auction_b1_p = stock['b1_v']
            stock_realtime_info.call_auction_b1_v = stock['b1_p']
            # 卖2
            stock_realtime_info.call_auction_b2_p = stock['b2_v']
            stock_realtime_info.call_auction_b2_v = stock['b2_p']
            # 卖3
            stock_realtime_info.call_auction_b3_p = stock['b3_v']
            stock_realtime_info.call_auction_b3_v = stock['b3_p']
            # 卖4
            stock_realtime_info.call_auction_b4_p = stock['b4_v']
            stock_realtime_info.call_auction_b4_v = stock['b4_p']
            # 卖5
            stock_realtime_info.call_auction_b5_p = stock['b5_v']
            stock_realtime_info.call_auction_b5_v = stock['b5_p']

            stock_realtime_info.save()


@periodic_task(run_every=1)
def update_myscrash():
    '''
    更新持仓数据
    :return:
    '''
    mystocks = stocksys_models.OpenInterests.objects.all()
    for mystock in mystocks:
        _stock = mystock.stock.stock
        stock_code = "%s%s" % (_stock.exchange_address.stock_sina_name, _stock.code)
        try:
            # 通过新浪API获取实时数据
            stock = get_realtime_stock_content(stock_code)
            # 将实时数据更新到数据库
            stock_realtime_info = mystock.stock
            stock_realtime_info.today_open = stock['open']
            stock_realtime_info.yestoday_close = stock['close']
            stock_realtime_info.current_price = stock['current']
            stock_realtime_info.high = stock['high']
            stock_realtime_info.low = stock['low']
            stock_realtime_info.volume = stock['v_num']
            stock_realtime_info.money = stock['money']
            # 买1
            stock_realtime_info.call_auction_a1_p = stock['a1_v']
            stock_realtime_info.call_auction_a1_v = stock['a1_p']
            # 买2
            stock_realtime_info.call_auction_a2_p = stock['a2_v']
            stock_realtime_info.call_auction_a2_v = stock['a2_p']
            # 买3
            stock_realtime_info.call_auction_a3_p = stock['a3_v']
            stock_realtime_info.call_auction_a3_v = stock['a3_p']
            # 买4
            stock_realtime_info.call_auction_a4_p = stock['a4_v']
            stock_realtime_info.call_auction_a4_v = stock['a4_p']
            # 买5
            stock_realtime_info.call_auction_a5_p = stock['a5_v']
            stock_realtime_info.call_auction_a5_v = stock['a5_p']

            # 卖1
            stock_realtime_info.call_auction_b1_p = stock['b1_v']
            stock_realtime_info.call_auction_b1_v = stock['b1_p']
            # 卖2
            stock_realtime_info.call_auction_b2_p = stock['b2_v']
            stock_realtime_info.call_auction_b2_v = stock['b2_p']
            # 卖3
            stock_realtime_info.call_auction_b3_p = stock['b3_v']
            stock_realtime_info.call_auction_b3_v = stock['b3_p']
            # 卖4
            stock_realtime_info.call_auction_b4_p = stock['b4_v']
            stock_realtime_info.call_auction_b4_v = stock['b4_p']
            # 卖5
            stock_realtime_info.call_auction_b5_p = stock['b5_v']
            stock_realtime_info.call_auction_b5_v = stock['b5_p']

            stock_realtime_info.save()

        except Exception as e:
            print("%s %s请求异常，跳过" % (stock_code, str(e)))
            continue


@periodic_task(run_every=1)
def update_order():
    '''
    更新订单数据
    :return:
    '''
    if onMarketOpenWork():
    # if True:
        undo_order = stocksys_models.OrderState.objects.get(state=0)  # 查找未完成订单
        orders = stocksys_models.CommitOrder.objects.filter(state_id=undo_order.id)
        for order in orders:
            sysconf = order.sysconf
            stock_info = order.stock_info
            _stock = stock_info.stock
            stock_code = "%s%s" % (_stock.exchange_address.stock_sina_name, _stock.code)

            skid_point = 0.00123  # 滑点
            try:
                # 通过新浪API获取实时数据
                stock_realtime_info = get_realtime_stock_content(stock_code)
                # 如果订单价格与实时价格相等
                if abs(order.price - stock_realtime_info['current']) < skid_point:
                    # 订单完成
                    order_state = stocksys_models.OrderState.objects.get(state=1)  # 创建完成类型订单
                    order.state = order_state
                    order.save()
                    # 交易税
                    commission_charge = (order.number * order.price) * sysconf.sh_price
                    if commission_charge < sysconf.sh_min_price:
                        commission_charge = sysconf.sh_min_price
                    # 买入订单的处理
                    if order.order_type.order_type == 0:
                        # 添加到持仓
                        # 如果当前股票已经有持仓则重新计算成本价
                        if stocksys_models.OpenInterests.objects.filter(stock=stock_info).count() != 0:
                            open_intrests = stocksys_models.OpenInterests.objects.get(stock=stock_info, sysconf=sysconf)
                            new_price = (
                                                open_intrests.price * open_intrests.number + order.price * order.number + commission_charge) / (
                                                order.number + open_intrests.number)
                            open_intrests.price = new_price
                            open_intrests.number += order.number
                            open_intrests.save()
                        else:
                            price = (order.price * order.number + commission_charge) / order.number
                            stocksys_models.OpenInterests.objects.create(stock=stock_info, sysconf=sysconf,
                                                                        number=order.number, price=price)
                        with open(settings.BASE_DIR + "/templates/stocksys/message/急速拉升.html") as template_file:
                            tpl = template.Template(template_file.read())
                            stock_realtime_info['addr'] = stock_code
                            context = template.Context({'stock': stock_realtime_info})
                            content = tpl.render(context)
                            title = '%s-%s交易成交' % (stock_info.stock.name, stock_info.stock.code)
                            send_email_message(title, content, [sysconf.user.email],"HTML")

                        sysconf.my_capital -= (order.number * order.price) - commission_charge
                        sysconf.save()
                    # 卖出订单的处理
                    elif order.order_type.order_type == 1:
                        # 持仓修改 T+1个交易日后清空持仓为0的股票
                        open_intrests = stocksys_models.OpenInterests.objects.get(stock=stock_info)
                        open_intrests.number -= order.number
                        open_intrests.save()

                        # 资金返回给用户
                        sysconf.my_capital += (order.number * order.price) - commission_charge
                        sysconf.save()

            except Exception as e:
                continue
            pass
